let createNewPromise = (url, params, promiseResolve) => {
    getApp().globalData.vxios.post(url, params)
        .then((res) => {
            promiseResolve(res.data);
        })
        .catch((err) => {
            console.log(err);
        })
}

let getResult = (url, params) => {
    let promiseTemp = null;
    let promiseResolve = null;

    async function fun() {
        promiseTemp = new Promise(resolve => promiseResolve = resolve);
        createNewPromise(url, params, promiseResolve);
        let res = await promiseTemp;
        return res;
    }
    return fun()
}

//使用微信号的code进行登录
const loginByWX = (code) => {
    let url = getApp().globalData.baseUrl + "user/login/wx";
    let params = {
        code: code
    }
    return getResult(url, params);
}

//绑定微信号
const bindWX = (code, token) => {
    wx.request({
        url: getApp().globalData.baseUrl + "user/bind/wx",
        header: {
            'context-type': 'application/json',
            'token': token
        },
        data: {
            code: code
        },
        method: "POST",
        success: (res) => {
            console.log(res);
        },
        fail: (err) => {
            console.log(err);
        }
    })
}

//使用用户名账号注册
const register = (username, password) => {
    let url = getApp().globalData.baseUrl + "user/register";
    let params = {
        username: username,
        password: password
    }
    return getResult(url, params);
}

//使用用户名账号登录
const login = (username, password) => {
    let url = getApp().globalData.baseUrl + "user/login";
    let params = {
        username: username,
        password: password
    }
    return getResult(url, params);
}

//退出登录
const exitLogin = () => {
    let header = {
        token: getApp().globalData.token
    }
    let url = getApp().globalData.baseUrl + "user/logout";
    wx.request({
        url: url,
        header: header,
        success: (res) => {
            console.log(res);
        },
        fail: (err) => {
            console.log(err);
        }
    })
    wx.removeStorage({
            key: 'token'
        })
        // getApp().globalData.vxios.get(url)
        // 	.then((res) =>{
        // 		console.log(res);
        // 	})
        // 	.catch((err) =>{
        // 		console.log(err);
        // 	})
}

export default {
    loginByWX,
    register,
    login,
    bindWX,
    exitLogin
}